package com.soulkun.smarthome.ui.main.personal

import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.soulkun.smarthome.R
import com.soulkun.smarthome.databinding.AppFragmentMainPersonalFamilyJoinBinding
import com.soulkun.smarthome.logic.enum.NavigationEnum
import com.soulkun.smarthome.ui.main.AppMainActivity
import com.soulkun.smarthome.ui.main.personal.viewmodel.AppMainPersonalFamilyCreateViewModel
import com.soulkun.smarthome.ui.main.personal.viewmodel.AppMainPersonalFamilyJoinViewModel
import soulkun.library.mvvm.component.BaseDataBindingFragment
import soulkun.library.utils.screen.ScreenUtils
import soulkun.library.utils.toast

class AppMainPersonalFamilyJoinFragment : BaseDataBindingFragment<AppFragmentMainPersonalFamilyJoinBinding>(){

    private lateinit var navigationEnum: NavigationEnum

    private val viewModel by viewModels<AppMainPersonalFamilyJoinViewModel> { defaultViewModelProviderFactory }

    override fun setLayout(): Int {
        return R.layout.app_fragment_main_personal_family_join
    }

    override fun initView() {
        if (navigationEnum == NavigationEnum.Main){
            ScreenUtils.setViewFitSystemWindows(requireDataBinding().root)
        }
    }

    override fun initData() {
        requireDataBinding().lifecycleOwner = viewLifecycleOwner
        requireDataBinding().viewModel = viewModel
        requireDataBinding().onClickListener = View.OnClickListener {
            when (it.id) {
                R.id.iv_main_personal_family_join_icon_code_join -> {
                    viewModel.joinFamily().observe(viewLifecycleOwner){ result ->
                        val result = result.getOrNull()
                        result?.statusMessage?.run {
                            toast()
                            when (navigationEnum) {
                                NavigationEnum.Splash -> {
                                    AppMainActivity.startIntentAnimationSlideVertical(mActivity)
                                    mActivity.finish()
                                }
                                NavigationEnum.Main -> {
                                    findNavController().navigateUp()
                                }
                            }
                        }
                    }
                }
                R.id.iv_main_personal_family_join_icon_back -> {
                    findNavController().navigateUp()
                }
            }
        }
    }

    override fun initListener() {
    }

    override fun doOnCreate() {
        navigationEnum =
            arguments?.getSerializable("navigationType") as NavigationEnum
    }
}